package com.weather.domen.impl;

import com.weather.domen.AreaDomeService;
import com.weather.pojo.entity.AreaInfo;
import com.weather.pojo.entity.AreaDeviceRelation;
import com.weather.pojo.vo.AreaInfoVO;
import com.weather.service.IAreaDeviceRelationService;
import com.weather.service.IAreaInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class AreaDomeServiceImpl implements AreaDomeService {
    @Resource
    private IAreaInfoService areaInfoService;

    @Resource
    private IAreaDeviceRelationService areaDeviceRelationService;


    @Override
    public List<AreaInfoVO> getAreaInfoList() {
        List<AreaInfo> areaInfoList = areaInfoService.list();
        List<AreaDeviceRelation> areaDeviceRelationList = areaDeviceRelationService.list();

        Map<Long, Integer> areaDeviceCountMap = areaDeviceRelationList.stream()
                .collect(Collectors.groupingBy(AreaDeviceRelation::getAreaId, Collectors.summingInt(relation -> 1)));


        List<AreaInfoVO> areaInfoVOList = new ArrayList<>();
        for (AreaInfo areaInfo : areaInfoList) {
            AreaInfoVO areaInfoVO = new AreaInfoVO();
            BeanUtils.copyProperties(areaInfo, areaInfoVO);
            areaInfoVO.setDeviceRelationCount(areaDeviceCountMap.getOrDefault(areaInfo.getAreaId(), 0));
            areaInfoVOList.add(areaInfoVO);
        }

        return areaInfoVOList;
    }

    @Override
    public boolean addAreaInfo(AreaInfo areaInfo) {
        return areaInfoService.save(areaInfo);
    }

    @Override
    public boolean updateAreaInfo(AreaInfo areaInfo) {
        return areaInfoService.updateById(areaInfo);
    }

    @Override
    public boolean deleteAreaInfo(Long areaId) {
        // Check if there are any associated devices
        QueryWrapper<AreaDeviceRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("area_id", areaId);
        long deviceCount = areaDeviceRelationService.count(queryWrapper);

        if (deviceCount > 0) {
            // Cannot delete if there are associated devices
            throw new RuntimeException("Cannot delete if there are associated devices");
        }

        // Delete the area if no associated devices
        return areaInfoService.removeById(areaId);
    }
}